//
//  HomePageView.m
//  LabanBrowser
//
//  Created by -Xh- on 3/13/13.
//  Copyright (c) 2013 VNG. All rights reserved.
//

#import "HomePageViewController.h"
#import "DialerView.h"
#import "MyUtilities.h"
#import "UIViewController+SGBrowserViewController.h"
#import "CustomPageControl.h"
#import "StaticVariables.h"
@implementation HomePageViewController{
    UIImage* plusImage;
    
    NSIndexPath* currentLongPressingIndexPath;
    NSMutableArray* presetWebViewURLOnHomePageArray;

    
}
@synthesize viewList;
@synthesize scrollView;
@synthesize dialer;
@synthesize delegate;
@synthesize pageControl;
@synthesize dialerURLDict;
@synthesize currentLongPressingSpeedDial;

@synthesize lastURL;
double kHomePageControlHeight=10;
int kMaxNumberOfWebView=3;


-(void)initialize:(CGRect)frame{
    self.title = [MyUtilities getLocalizeStringFromTag:@"HomePageTitle"];
    viewList=[[NSMutableArray alloc]init];
    
    double shrinkHeight=self.view.bounds.size.height-kHomePageControlHeight;
    CGRect scrollRect=CGRectMake(0, 0, frame.size.width, shrinkHeight);
    scrollView=[[UIScrollView alloc]initWithFrame:scrollRect];
    //scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    scrollView.pagingEnabled = YES;//UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone;
    [scrollView setShowsHorizontalScrollIndicator:NO];
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    scrollView.clipsToBounds=YES;
    scrollView.bounces=NO;
    scrollView.delaysContentTouches=NO;
    scrollView.canCancelContentTouches=YES;
    scrollView.scrollsToTop = NO;
    scrollView.scrollEnabled=YES;
    scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: scrollView];
    scrollView.delegate=self;
    
    
    
    
    CGRect dialerRect=CGRectMake(frame.size.width, 0, frame.size.width, shrinkHeight);
    dialer=[[DialerView alloc]initWithFrame:dialerRect];
    dialer.delegate=self;
    dialer.dataSource=self;
    
    //dialer.backgroundColor=[UIColor blueColor];
    plusImage=[UIImage imageNamed:@"bg_browser_homeview_content_speedial_item_add_nor.png"];
    
    presetWebViewURLOnHomePageArray=[[NSMutableArray alloc]init];
    [presetWebViewURLOnHomePageArray addObject:@"http://m.laban.vn/b/"];
    [presetWebViewURLOnHomePageArray addObject:@"http://m.laban.vn/b/tienich"];
    [presetWebViewURLOnHomePageArray addObject:@"http://l.baomoi.com/"];
    
    
    
    
    
    [self loadAllSite];
    
    
    pageControl=[[CustomPageControl alloc]initWithFrame:CGRectMake(0, shrinkHeight, frame.size.width, kHomePageControlHeight)];
    [self.view addSubview:pageControl];
    pageControl.numberOfPages=viewList.count;
    pageControl.currentPage=1;
    pageControl.backgroundColor=[UIColor whiteColor];
    //pageControl
    pageControl.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    pageControl.delegate = self;
    
    
    [scrollView setContentSize:CGSizeMake(frame.size.width*viewList.count, self.scrollView.bounds.size.height)];
    [scrollView scrollRectToVisible:dialer.frame animated:NO];
    
    
    [self.dialer populateSpeedDialFromDB];
    
    UILongPressGestureRecognizer* longPressGR=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressOnCell:)];
    longPressGR.minimumPressDuration=0.7f;
    [self.dialer addGestureRecognizer:longPressGR];
    dialerURLDict=[[NSMutableDictionary alloc]init];
    
    //lastURL = nil;
    //[self addGestureRecognizer:tapGR];
    
    //self.scrollView.layer.borderColor=[[UIColor blackColor]CGColor];
    //self.scrollView.layer.borderWidth=2;
    
    //self.presenterView.layer.borderColor=[[UIColor redColor]CGColor];
    //self.presenterView.layer.borderWidth=2;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    CGRect curFrame = self.view.frame;
    curFrame.size.height = self.browserViewController.view.frame.size.height - 85;
    self.view.frame = curFrame;
    [self initialize:self.view.frame];
}
-(void)viewWillAppear:(BOOL)animated{
    [self arrangeChildren];
}

-(void)onTapHomePage:(UITapGestureRecognizer*)_gesture{
    if(delegate && [delegate respondsToSelector:@selector(onTapNoWhere)]){
        [delegate onTapNoWhere];
    }
}



-(void)loadAllSite{
    double shrinkHeight=self.view.bounds.size.height-kHomePageControlHeight;
    
    for(int i=0;i<kMaxNumberOfWebView;i++){
        int kTimes=i;
        if(i!=0){
            kTimes=i+1;
        }
        UIWebView* iWV=[[UIWebView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width*kTimes, 0, self.view.bounds.size.width, shrinkHeight)];
        iWV.scrollView.scrollsToTop = NO;
        //iWV.backgroundColor=[UIColor greenColor];
        iWV.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        //[iWV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[presetWebViewURLOnHomePageArray objectAtIndex:i]] ]];
        [scrollView addSubview:iWV];
        [viewList addObject:iWV];//abc
        iWV.delegate=self;
        
        if(i==0){
            [scrollView addSubview:dialer];
            [viewList addObject:dialer];
            
        }
    }
}

-(void)addToDictWithURL:(NSString*)_url AndIndexPath:(NSIndexPath*)_indexPath{
    if([dialerURLDict objectForKey:_url]==nil){
        [dialerURLDict setObject:_indexPath forKey:_url];
    }
    
}

-(BOOL)isPresentingDialer{
    return pageControl.currentPage==1;
}

-(void)reflowDialerWhenGoingBackFromSettings{
    double shrinkHeight=self.view.bounds.size.height-kHomePageControlHeight;
    CGRect dialerFrame = self.dialer.frame;
    dialerFrame.size.width = self.view.frame.size.width;
    dialerFrame.size.height = shrinkHeight;
    self.dialer.frame = dialerFrame;
    
}

#pragma mark viewController
-(void)animateToRect:(CGRect)_rect{
    CGRect svRect = self.scrollView.frame;
    svRect.size.width = _rect.size.width;
    svRect.size.height = _rect.size.height;
    self.scrollView.frame = svRect;
    CGRect pcRect = self.pageControl.frame;
    pcRect.origin.y = _rect.origin.y + _rect.size.height - kHomePageControlHeight;
    self.pageControl.frame = pcRect;
    CGRect dialerRect = self.dialer.frame;
    dialerRect.size.height = _rect.size.height;
    self.dialer.frame = dialerRect;
}

-(void)arrangeChildren{
//    CGRect curFrame = self.view.frame;
//    curFrame.size.height = self.browserViewController.view.frame.size.height - 85;
//    self.view.frame = curFrame;
    
    
//    CGRect svFrame = self.scrollView.frame;
//    svFrame.size.width = self.view.frame.size.width;
//    svFrame.size.height = self.view.frame.size.height;
//    self.scrollView.frame = svFrame;    
    
//    pageControl.frame = CGRectMake(0, svFrame.size.height - kHomePageControlHeight, svFrame.size.width, kHomePageControlHeight);
    [pageControl setNeedsDisplay];

   
    for(int i = 0; i<viewList.count; i++){
        UIView* iChild = [viewList objectAtIndex:i];
        iChild.frame = CGRectMake(self.view.bounds.size.width * i, 0, self.view.bounds.size.width, self.scrollView.bounds.size.height);
        //[MyUtilities logRect:iChild.frame withTag:[NSString stringWithFormat:@"%i",i]];
    }
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * viewList.count, 1);
    self.scrollView.contentOffset = CGPointMake(self.view.bounds.size.width * self.pageControl.currentPage, 0);
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    int currentOrientation = [[[[StaticVariables shareVariables]userDefaults]orientation]intValue];
    if(currentOrientation == 1 || currentOrientation == 2 || currentOrientation == 3){
        return NO;
    }else{
        return interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
    }
    //return YES;

}

- (NSUInteger)supportedInterfaceOrientations {
    int currentOrientation = [[[[StaticVariables shareVariables]userDefaults]orientation]intValue];
    return [[[[[StaticVariables shareVariables]settingsData]orientationValues]objectAtIndex:currentOrientation]intValue];
    //return UIInterfaceOrientationMaskAll;
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    self.scrollView.delegate = nil;
}
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self arrangeChildren];
//    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * viewList.count, 1);
//    self.scrollView.contentOffset = CGPointMake(self.view.bounds.size.width * self.pageControl.currentPage, 0);
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    //self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width + SG_TAB_WIDTH, self.scrollView.bounds.size.height);
    
    [self arrangeChildren];
    self.scrollView.delegate = self;
}

#pragma mark fullScreen Stuffs
//-(void)onFullScreenPreAdjustExceptItemAtIndex:(int)_index WithExpandAmount:(double)_amount{
//
//    
//    //adjust the rest
//    for(int i=0;i<viewList.count;i++){
//        UIView* iView=[viewList objectAtIndex:i];
//        if(_index==-1){
//            CGRect iRect=iView.frame;
//            iRect.size.height+=_amount;
//            iView.frame=iRect;
//            
//        }else{
//            if(i!=_index){
//                CGRect iRect=iView.frame;
//                iRect.size.height+=_amount;
//                iView.frame=iRect;
//            }
//        }
//        
//    }
//    
//}
//-(void)onFullScreenAnimateItemAtIndex:(int)_index WithExpandAmount:(double)_amount{
//
//    //animate current
//    CGRect svFrame=self.scrollView.frame;
//    svFrame.size.height+=_amount;
//
//    if(_index==-1){
//        
//    }else{
//        UIView* currentView=[viewList objectAtIndex:_index];
//        CGRect iRect=currentView.frame;
//        iRect.size.height+=_amount;
//        currentView.frame=iRect;
//    }
//    
//    CGRect pageControlRect=self.pageControl.frame;
//    pageControlRect.origin.y+=_amount;
//   
//    self.pageControl.frame=pageControlRect;
//    self.scrollView.frame=svFrame;
//    
//    [dialer reloadData];
//
//}

-(void)removeOtherSideViews{
    for(int i = 0;i < viewList.count; i++){
        if(i != self.pageControl.currentPage){
            [[viewList objectAtIndex:i] removeFromSuperview];
        }
    }
NSLog(@"Remove all side view, svCount = %i",self.scrollView.subviews.count);
}
-(void)recoverAllSideViews{
    for(int i = 0;i < viewList.count; i++){
        if(i != self.pageControl.currentPage){
            [self.scrollView insertSubview:[viewList objectAtIndex:i] atIndex:i];
        }
    }
    NSLog(@"Recover all side view, svCount = %i",self.scrollView.subviews.count);
}

#pragma customPageControlDelegate
-(void)pageControlPageDidChange:(CustomPageControl *)pageControl{
    NSLog(@"changed");
}


#pragma mark UISCrollViewDelegate
-(void)onPageChanged{
    int currentPage = self.pageControl.currentPage;
    if([[viewList objectAtIndex:currentPage] isKindOfClass:[UIWebView class]]){
        UIWebView* iWV = (UIWebView*)[viewList objectAtIndex:currentPage];
        if(iWV.request == nil){
            int urlIndex = currentPage;
            if(currentPage >= 2){
                urlIndex = currentPage - 1;
            }
            [iWV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[presetWebViewURLOnHomePageArray objectAtIndex:urlIndex]] ]];
            NSLog(@"load at %i : url = %@",currentPage, iWV.request.URL.absoluteString);

        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat pageWidth = self.scrollView.frame.size.width; // you need to have a **iVar** with getter for scrollView
    float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
    NSInteger page = lround(fractionalPage);
    int oldPage = self.pageControl.currentPage;
    self.pageControl.currentPage = page;
    int newPage = self.pageControl.currentPage;
    if(oldPage != newPage){
        [self onPageChanged];
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

#pragma mark CollectionView
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return dialer.speedDialList.count+1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    DialerItem* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"DialerReuseID" forIndexPath:indexPath];
    if(indexPath.row==dialer.speedDialList.count){
        cell.titleLabel.text=[MyUtilities getLocalizeStringFromTag:@"ActionAdd"];
        cell.thumbImage.image= plusImage;
        [cell needToShowBorder:NO];
    }else{
        [cell needToShowBorder:YES];
        //for data from db
        SpeedDialModel* currentSpeedDial=[dialer.speedDialList objectAtIndex:indexPath.row];
        //cell.backgroundColor=[UIColor whiteColor];
        UIImage* buttonImage;
        if(currentSpeedDial.favIcon==nil){
            buttonImage=[UIImage imageNamed:[[[StaticVariables shareVariables]presetDialerURLDic] objectForKey:currentSpeedDial.url]];
        }else{
            
            if(currentSpeedDial.favIcon.length == 2 || currentSpeedDial.favIcon.length == 0){ //nsdata 0 bytes add to db, they become 2 bytes??? Still just a workaround here
                buttonImage=[UIImage imageNamed:@"sd_blank.png"];
            }else{
                buttonImage=[UIImage imageWithData:currentSpeedDial.favIcon];
                
            }
        }
        cell.thumbImage.image=buttonImage;
        cell.titleLabel.text=currentSpeedDial.title;
        
        //cell.thumbImage.layer.borderWidth=1;
        //cell.thumbImage.layer.borderColor=[[UIColor blackColor]CGColor];
        [self addToDictWithURL:currentSpeedDial.url AndIndexPath:indexPath];
    }
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==dialer.speedDialList.count){
        if(delegate && [delegate respondsToSelector:@selector(onAddingNewSpeedDial)]){
            [delegate onAddingNewSpeedDial];
        }
    }else{
        /*
        if(delegate && [delegate respondsToSelector:@selector(onSpeedDialAtItem:)]){
            SpeedDialModel* currentSpeedDial=[dialer.speedDialList objectAtIndex:indexPath.row];
            
            [delegate onSpeedDialAtItem:currentSpeedDial];
        }
         */
         SpeedDialModel* currentSpeedDial=[dialer.speedDialList objectAtIndex:indexPath.row];
        [[self browserViewController] handleURLString:currentSpeedDial.url title:nil];
    }
    //[self collectionView:collectionView didHighlightItemAtIndexPath:indexPath];
    
}



-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    DialerItem* cell=(DialerItem*)[collectionView cellForItemAtIndexPath:indexPath];
    if(indexPath.row==dialer.speedDialList.count){
        cell.thumbImage.image=[UIImage imageNamed:@"bg_browser_homeview_content_speedial_item_add_hl.png"];
        [cell needToHighlightTextOnly:YES];
    }else{
        
        
        [cell needToHighlight:YES];
        
    }
}

-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    DialerItem* cell=(DialerItem*)[collectionView cellForItemAtIndexPath:indexPath];
    if(indexPath.row==dialer.speedDialList.count){
        cell.thumbImage.image=[UIImage imageNamed:@"bg_browser_homeview_content_speedial_item_add_nor.png"];
        [cell needToHighlightTextOnly:NO];
    }else{
        
        
        [cell needToHighlight:NO];
        
    }
}


-(void)handleLongPressOnCell:(UILongPressGestureRecognizer*)_gesture{
    if(_gesture.state==UIGestureRecognizerStateBegan){
        CGPoint pressLocation = [_gesture locationInView:self.dialer];
        currentLongPressingIndexPath= [self.dialer indexPathForItemAtPoint:pressLocation];
        
        if(currentLongPressingIndexPath.row!=dialer.speedDialList.count){
            currentLongPressingSpeedDial=[dialer.speedDialList objectAtIndex:currentLongPressingIndexPath.row];
            UIActionSheet* actionSheet;
            actionSheet=[[UIActionSheet alloc]initWithTitle:currentLongPressingSpeedDial.title
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ActionCancel", @"Cancel")
                                     destructiveButtonTitle:nil
                                          otherButtonTitles:[MyUtilities getLocalizeStringFromTag:@"ActionOpen"],
                         [MyUtilities getLocalizeStringFromTag:@"ActionOpenInNewTab"],
                         [MyUtilities getLocalizeStringFromTag:@"ActionEdit"],
                         [MyUtilities getLocalizeStringFromTag:@"ActionRemoveFromSpeedDial"],nil];
            [actionSheet showInView:self.browserViewController.view];
        }
        
    }
    
}
#pragma mark UIActionSheet

-(void)performUpdateWithModel:(SpeedDialModel*)_speedDial{
    [self.dialer performBatchUpdates:^{
        int replaceIndex=[self.dialer.speedDialList indexOfObject:[self.dialer speedDialByURL:_speedDial.url]];
        
        [self.dialer.speedDialList replaceObjectAtIndex:replaceIndex withObject:_speedDial];
        //[self.dialer.speedDialList removeObjectAtIndex:_indexPath.row];
        [self.dialer performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
        
        
        
    } completion:^(BOOL finished) {
        
    }];
    
}


//-(void)perform
-(void)performDeleteAtID:(NSString *)_id{
    //self.dialer.speedDialList
//    [self.dialer.speedDialList removeObject:[self.dialer speedDialByID:_id]];
//    [self.dialer performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    NSLog(@"performDelete");
    
}

-(void)performInsertWithAnimation:(SpeedDialModel*)_speedDial{
    [self.dialer performBatchUpdates:^{
        [self.dialer insertSpeedDial:_speedDial];
    } completion:^(BOOL finished) {
        //double toolbarHeight=40;
        //UIImage* cloneDialerImage=[MyUtilities takeScreenShotOfView:self WithOffset:CGPointMake(0, toolbarHeight)];
        //[[[StaticVariables shareVariables]imageGallery]setHomeCloneImage:cloneDialerImage];
    }];
}

-(void)performDeleteAtIndexPath:(NSIndexPath *)_indexPath{
    [self.dialer performBatchUpdates:^{
        
        [self.dialer deleteItemsAtIndexPaths:[NSArray arrayWithObject:_indexPath]];
        [self.dialer.speedDialList removeObjectAtIndex:_indexPath.row];
        
    } completion:^(BOOL finished) {
        //double toolbarHeight=[[[StaticVariables shareVariables]constantValues]toolBarHeight];
        //UIImage* cloneDialerImage=[MyUtilities takeScreenShotOfView:self WithOffset:CGPointMake(0, toolbarHeight)];
        //[[[StaticVariables shareVariables]imageGallery]setHomeCloneImage:cloneDialerImage];
    }];
}
-(void)performInsert:(SpeedDialModel *)_speedDial{
    [self.dialer.speedDialList addObject:_speedDial];
    [self.dialer performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    NSString* buttonTitle=[actionSheet buttonTitleAtIndex:buttonIndex];
    
    if([buttonTitle isEqualToString:[MyUtilities getLocalizeStringFromTag:@"ActionOpen"]]){
        [self.browserViewController handleURLString:currentLongPressingSpeedDial.url title:currentLongPressingSpeedDial.title];
    }
    
    
    if([buttonTitle isEqualToString:[MyUtilities getLocalizeStringFromTag:@"ActionOpenInNewTab"]]){
        [self.browserViewController addTabWithURL:[NSURL URLWithString:currentLongPressingSpeedDial.url] withTitle:currentLongPressingSpeedDial.title];
    }
    //actionRemoveFromSpeedDial
    if([buttonTitle isEqualToString:[MyUtilities getLocalizeStringFromTag:@"ActionRemoveFromSpeedDial"]]){
        //[self performDelete];
        [[[StaticVariables shareVariables]speedDialAccess] deleteObjectAtURL:currentLongPressingSpeedDial.url];
       // [[[StaticVariables shareVariables]historyAccess]setSpeedDial:0 atID:currentLongPressingSpeedDial.historyID];
        
//        if(delegate && [delegate respondsToSelector:@selector(onDeleteOnHomePageAtIndexPath:)]){
//            [delegate onDeleteOnHomePageAtIndexPath:currentLongPressingIndexPath];
//        }
        [self performDeleteAtIndexPath:currentLongPressingIndexPath];
    }
    
    if([buttonTitle isEqualToString:[MyUtilities getLocalizeStringFromTag:@"ActionEdit"]]){
        if(delegate && [delegate respondsToSelector:@selector(onHomePageEditAtIndexPath:AndModel:)]){
            [delegate onHomePageEditAtIndexPath:currentLongPressingIndexPath AndModel:currentLongPressingSpeedDial];
        }
    }
    
    
}


#pragma mark webviewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString* urlString=[[request URL]absoluteString];
    BOOL shouldLoad=NO;
    for(int i=0;i<presetWebViewURLOnHomePageArray.count;i++){
        NSString* siteString=[presetWebViewURLOnHomePageArray objectAtIndex:i];
        if([urlString rangeOfString:siteString].location!=NSNotFound){
            shouldLoad=YES;
            break;
        }
    }
    
    if(shouldLoad==NO){
        //[self.browser handleURLString:searchString title:title];
        [[self browserViewController] handleURLString:urlString title:nil];
    }
    return shouldLoad;
}
 

@end
